using System;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace PS.WebParts.Rollup.Core
{
    class SPWebCache : IDisposable
    {
        private readonly Dictionary<Guid, SPWeb> list;
        private readonly SPSite site;
        private readonly Guid curWebID = Guid.Empty;
        private int c;

        public SPWebCache(SPWeb web) 
        {
            this.curWebID = web.ID;
            this.site = web.Site;
            list = new Dictionary<Guid, SPWeb>(128);
            list.Add(web.ID, web);
        }

        public SPWebCache(SPSite site)
        {
            this.site = site;
            list = new Dictionary<Guid, SPWeb>(128);
        }

        public SPWeb Get(Guid id)
        {
            SPWeb obj;
            if (!list.ContainsKey(id))
            {
                obj = site.OpenWeb(id);
                list.Add(id, obj);
                c++;
            }
            else
            {
                obj = list[id];
            }
            return obj;
        }


        public void Dispose()
        {
            foreach (KeyValuePair<Guid, SPWeb> w in list)
            {
                if (w.Key != curWebID) //do not dispose of the obj originally supplied through constructor
                {
                    c--;
                    try
                    {
                        w.Value.Dispose();
                    }
                    catch (SPException)
                    {
                    }
                }
            }

            if (c != 0)
                throw new ApplicationException("Not all objects were disposed");
        }
    }
}
